package com.kx.kxpicture.manager;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpStatus;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import com.kx.kxpicture.config.CosClientConfig;
import com.kx.kxpicture.exception.BusinessException;
import com.kx.kxpicture.exception.ErrorCode;
import com.kx.kxpicture.exception.ThrowsUtils;
import com.kx.kxpicture.model.dto.file.UploadPictureResult;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.model.ciModel.persistence.ImageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.amqp.RabbitStreamTemplateConfigurer;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * 图片上传通用类
 *
 * @author kuangxin
 * date 2025/8/28
 */
@Service
@Slf4j
@Deprecated
public class FileManager {
    @Resource
    private CosClientConfig cosClientConfig;

    @Resource
    private CosManager cosManager;

    /**
     * 上传图片
     * @param multipartFile
     * @param uploadPrefix 图片相对路径
     * @return
     */
    public UploadPictureResult uploadPictureResult(MultipartFile multipartFile,String uploadPrefix){
        validPicture(multipartFile);
        String uuid = RandomUtil.randomString(16);
        String originalFilename = multipartFile.getOriginalFilename();
        //上传的文件名=日期+uuid+文件名
        String safeDate = DateUtil.format(new Date(), "yyyy-MM-dd_HH-mm-ss");
        String uploadFileName = String.format("%s_%s_%s", safeDate,uuid,FileUtil.getSuffix(originalFilename));
        //上传路径
        String uploadPath = String.format("/%s/%s",uploadPrefix,uploadFileName);
        File file=null;

        try {
            //图片保存
            file = File.createTempFile(uploadPath,null);
            multipartFile.transferTo(file);
            PutObjectResult putObjectResult = cosManager.putPictureObject(uploadPath, file);
            ImageInfo imageInfo = putObjectResult.getCiUploadResult().getOriginalInfo().getImageInfo();
            String format = imageInfo.getFormat();
            int width = imageInfo.getWidth();
            int height = imageInfo.getHeight();
            double scale = NumberUtil.round(width*1.0/height,2).doubleValue();
            UploadPictureResult uploadPictureResult = new UploadPictureResult();
            uploadPictureResult.setUrl(cosClientConfig.getHost()+"/"+uploadPath);
            uploadPictureResult.setPicName(FileUtil.mainName(originalFilename));
            uploadPictureResult.setPicSize(FileUtil.size(file));
            uploadPictureResult.setPicWidth(width);
            uploadPictureResult.setPicHeight(height);
            uploadPictureResult.setPicScale(scale);
            uploadPictureResult.setPicFormat(format);
            return uploadPictureResult;
        }catch (Exception e){
            log.error("图片上传失败{}",e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"图片上传失败");
        }finally {
            deleteFile(file);
        }
        }



    /**
     * 图片检验
     * @param multipartFile
     */
    private void validPicture(MultipartFile multipartFile) {
        ThrowsUtils.throwIf(multipartFile==null, ErrorCode.PARAMS_ERROR,"文件不能为空");
        long fileSize = multipartFile.getSize();
        final long ONE_M=1024*1024L;
        ThrowsUtils.throwIf(fileSize>2*ONE_M,ErrorCode.PARAMS_ERROR,"大小不能超过2M");
        //得到文件后缀
        String fileSuffix = FileUtil.getSuffix(multipartFile.getOriginalFilename());
        final List<String> ALLOW_FORMAT_LIST= Arrays.asList("jpeg","jpg","png","webp");
        ThrowsUtils.throwIf(!ALLOW_FORMAT_LIST.contains(fileSuffix),ErrorCode.PARAMS_ERROR,"文件类型错误");
    }

    private  void deleteFile(File file) {
        if (file==null){
            return;
        }
        boolean delete = file.delete();
        if (!delete){
            log.error("文件删除错误，filepath={}", file.getAbsolutePath());
        }
    }


    /**
     * 通过url下载图片
     *
     * @param fileUrl      url路径
     * @param uploadPrefix 相对路径
     * @return
     */
    public UploadPictureResult uploadPictureByUrl(String fileUrl, String uploadPrefix) {
        //校验图片 todo
        validPicture(fileUrl);
        String uuid = RandomUtil.randomString(16);
        String originalFilename = FileUtil.mainName(fileUrl);
        //上传的文件名=日期+uuid+文件名
        String safeDate = DateUtil.format(new Date(), "yyyy-MM-dd_HH-mm-ss");
        String uploadFileName = String.format("%s_%s_%s", safeDate, uuid, FileUtil.getSuffix(originalFilename));
        //上传路径
        String uploadPath = String.format("/%s/%s", uploadPrefix, uploadFileName);
        File file = null;

        try {
            //图片保存
            file = File.createTempFile(uploadPath, null);
            HttpUtil.downloadFile(fileUrl, file);
            PutObjectResult putObjectResult = cosManager.putPictureObject(uploadPath, file);
            ImageInfo imageInfo = putObjectResult.getCiUploadResult().getOriginalInfo().getImageInfo();
            String format = imageInfo.getFormat();
            int width = imageInfo.getWidth();
            int height = imageInfo.getHeight();
            double scale = NumberUtil.round(width * 1.0 / height, 2).doubleValue();
            UploadPictureResult uploadPictureResult = new UploadPictureResult();
            uploadPictureResult.setUrl(cosClientConfig.getHost() + "/" + uploadPath);
            uploadPictureResult.setPicName(FileUtil.mainName(originalFilename));
            uploadPictureResult.setPicSize(FileUtil.size(file));
            uploadPictureResult.setPicWidth(width);
            uploadPictureResult.setPicHeight(height);
            uploadPictureResult.setPicScale(scale);
            uploadPictureResult.setPicFormat(format);
            return uploadPictureResult;
        } catch (Exception e) {
            log.error("图片上传失败{}", e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "图片上传失败");
        } finally {
            deleteFile(file);
        }
    }

    /**
     * 通过url校验图片
     *
     * @param fileUrl
     */
    private void validPicture(String fileUrl) {
        ThrowsUtils.throwIf(StrUtil.isBlank(fileUrl), ErrorCode.PARAMS_ERROR, "文件地址不能为空");
        //校验url格式
        try {
            new URL(fileUrl);
        } catch (MalformedURLException e) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件地址格式不正确");
        }
        //校验url协议 http//https
        ThrowsUtils.throwIf(!fileUrl.startsWith("http://") || !fileUrl.startsWith("https://"), ErrorCode.PARAMS_ERROR, "url协议错误");
        //文件是否存在
        HttpResponse response = null;

        try {
            response = HttpUtil.createRequest(Method.HEAD, fileUrl).execute();
            if (response.getStatus() != HttpStatus.HTTP_OK) {
                return;
            }
            String contentType = response.header("Content-Type");
            if (StrUtil.isNotBlank(contentType)) {
                final List<String> ALLOW_CONTENT_TYPES = Arrays.asList("image/jpeg", "image/jpg", "image/png", "image/webp");
                ThrowsUtils.throwIf(!ALLOW_CONTENT_TYPES.contains(contentType.toLowerCase()),
                        ErrorCode.PARAMS_ERROR, "文件类型错误");
            }
            String fileLength = response.header("Content-Length");
            if (StrUtil.isNotBlank(fileLength)) {
                try {
                    long contentLength = Long.parseLong(fileLength);
                    final long TWO_MB = 2 * 1024 * 1024L;
                    ThrowsUtils.throwIf(contentLength > TWO_MB, ErrorCode.PARAMS_ERROR, "文件大小不能超过 2M");
                } catch (NumberFormatException e) {
                    throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件大小格式错误");
                }
            }
        } finally {
            if (response != null) {
                response.close();
            }
        }
    }


}
